package com.dsx.haha.servicempl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsx.haha.mapper.TenantMapper;
import com.dsx.haha.mapper.TenantUserMapper;
import com.dsx.haha.mapper.UserMapper;
import com.dsx.haha.model.entity.Tenant;
import com.dsx.haha.model.entity.TenantUser;
import com.dsx.haha.model.entity.User;
import com.dsx.haha.model.vo.TenantVo;
import com.dsx.haha.service.TenantService;
import com.dsx.haha.utils.Md5Util;
import com.dsx.haha.utils.RedPrint;
import com.dsx.haha.utils.UuidUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dsx
 * @date 2021/3/11 13:48
 * @since JDK1.8
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
    @Autowired
    TenantMapper tenantMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TenantUserMapper tenantUserMapper;
    
    @Override
    public TenantMapper getTenantMapper() {
        return tenantMapper;
    }

    //添加前端注册的租户到数据库中err
    @Override
    public int addTenant(TenantVo tenantVo) {
        System.err.println("tenantVo："+tenantVo.toString());
    //插入租户信息=======================================
        Tenant tenant = new Tenant();
        BeanUtils.copyProperties(tenantVo,tenant);
        tenant.setCreateTime(new Date());   //租户创建时间
        String id= UuidUtils.getUuid();  //租户id
        tenant.setId(id);
        tenantMapper.insertTenant(tenant);//插入数据

        RedPrint.print("1插入租户信息成功！！！");
       

    //插入创建租户的用户信息=======================================    
        User user = new User();
        user.setId(id);
        user.setUserName(tenant.getTenantName());
        user.setUserPwd(tenantVo.getPwd());
        //密码加密
        //user.setUserPwd(Md5Util.getMd5(tenantVo.getCreatePwd().trim(),tenantVo.getCreateMan().trim()));
        user.setJoinDate(tenant.getCreateTime());
        userMapper.addUser(user);
        RedPrint.print("=====2插入创建租户成功====");

    //插入租户-用户信息=======================================    
        TenantUser tenantUser = new TenantUser();
        tenantUser.setId(UuidUtils.getUuid());
        tenantUser.setTenantId(id);
        tenantUser.setUserId(id);
        tenantUser.setCreateTime(tenant.getCreateTime());
        RedPrint.print(tenantUser.toString());
        tenantUserMapper.addTenantUser(tenantUser);
        RedPrint.print("====3租户-用户关系建立成功====");

    //插入租户自己的用户角色信息=======================================    
        //使用万能map
        Map<String, Object> map = new HashMap<>();
        map.put("uid",id);
        map.put("role_id","1");
        int i = userMapper.addUserRole(map);
        RedPrint.print("====4插入租户自己的用户角色信息成功===="+"\t"+i);

        return 1;
    }

    
}
